<!-- 人员 -->
<template>
    <div class="departUsers" v-loading="loading">
        <dy-table :elTable_Options="elTable_Options" @handleClick="handleClick" @bottonHandle="bottonHandle"
            ref="table" />
        <!-- 公共弹框 -->
        <choose-component :choseData="choseData" ref="mychildchooseComponent" @inputsydata="inputsydata"
            v-if="modalStatus == '公共选择弹窗'" />
        <!-- 选择角色 -->
        <choose-role ref="mychooserole" v-if="modalStatus === '切换角色'" @submitHandle="submitHandle" />
    </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
import { useCach } from '@/store/cach'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref, computed, nextTick, toRefs, onMounted } from 'vue'
import api from '@/api'
import commonV from '@/common'

const route = useRoute()
const router = useRouter()

let pageConfig = useCach()
let departmentRoles = computed(() => pageConfig.departmentRoles)
let modalStatus = computed(() => pageConfig.modalStatus)

let state = reactive({
    loading: false,
    choseData: null,
    currentRow: null
})
let {
    loading, choseData
} = toRefs(state)

let elTable_Options = reactive({
    pagename: '用户信息列表',
    selection: false, //多选
    name: "username",
    //获取方法
    getwayname: "users",
    //操作button
    opbutton: [{
        label: '返回',
        dealway: 'returnP',
        icon: 'Back',
        plain: true
    }, {
        label: '添加成员',
        dealway: 'addUsers',
        icon: 'Plus',
        type: 'primary'
    }, {
        label: '批量删除',
        dealway: 'asysdeleterow',
        icon: 'Delete',
        type: 'danger',
        plain: true
    }],
    //列表表头
    eltableArr: [{
        label: "用户名",
        prop: "username",
        columType: 'text',
    },
    {
        label: "真实姓名",
        prop: "real_name",
        columType: 'text'
    },
    {
        label: "科室",
        prop: "departmentarr",
        columType: 'arrkey',
        keyName: "department_name"
    }, {
        label: "角色",
        prop: "roleArr",
        columType: 'arrkey',
        keyName: "role_name"
    }, {
        label: "操作",
        prop: "",
        width: 120,
        fixed: "right",
        columType: 'opreatebar',
        operation: [{
            op_name: "移动",
            op_index: "4",
            color: "#20A0FF"
        }, {
            op_name: "删除",
            op_index: "5",
            color: "#FF4949"
        }]
    }],
    //查询栏
    searchList: [{
        label: "姓名",
        key: "real_name",
        searchtype: 'input',
        width: 240
    }, {
        label: "用户名",
        key: "username",
        searchtype: 'input',
        width: 240
    }],
})

let table = ref(null)
let mychildchooseComponent = ref(null)
let mychooserole = ref(null)

onMounted(() => {
    openFunction()
})

let handleClick = (row, index) => {
    if (index == '4') {
        //移动
        pageConfig.changeShowModal(true)
        pageConfig.changeModalStatus("切换角色")
        nextTick(() => {
            state.currentRow = JSON.parse(JSON.stringify(row))
            mychooserole.value.openFunction(row)
        })
    } else if (index == '5') {
        //删除
        ElMessageBox.confirm("确定从此角色中删除此用户?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
        }).then(async () => {
            state.loading = true
            let params = {
                role_id: route.query.id,
                user_ids: [row.id]
            }
            await api.changeaxiosdata("delete_role_user", "post", params)
            ElMessage({
                message: '操作成功!',
                type: 'success'
            })
            gettabledata()
            state.loading = false
        }).catch(() => { })
    }
}

let bottonHandle = (wayname) => {
    if (wayname == 'returnP') {
        //返回
        router.push({
            path: "/systemManage/departmentMan"
        })
    } else if (wayname == 'asysdeleterow') {
        //批量删除
        asysdeleterow()
    } else if (wayname == 'addUsers') {
        //添加人员
        addUsers()
    }
}

//添加人员
let addUsers = async () => {
    state.choseData = commonV.chooseComponent.choseuserData
    state.choseData.singleFlag = false //人员多选
    pageConfig.changeShowModal(true)
    pageConfig.changeModalStatus("公共选择弹窗")
    nextTick(() => {
        let res = table.value.tableIntance.state.tableData
        if (commonV.ifvalidArr(res)) {
            res = JSON.parse(JSON.stringify(res))
        }
        mychildchooseComponent.value.openFunction(res)
    })
}

//添加人员回调
let inputsydata = async (selectArr) => {
    state.loading = true
    let ids = []
    selectArr.forEach(it => ids.push(it.id)) //获取id
    let params = {
        role_id: route.query.id,
        user_ids: ids
    }
    let res = await api.changeaxiosdata("create_role_user", "post", params)
    if (res) {
        ElMessage({
            message: '添加人员成功!',
            type: 'success'
        })
        gettabledata() //重新获取数据
    }
    state.loading = false
}

//批量删除
let asysdeleterow = () => {
    let selectArr = table.value.tableIntance.state.selection
    if (!selectArr.length) {
        ElMessage({
            message: '请选择删除项',
            type: 'warning'
        })
        return
    }
    ElMessageBox.confirm("确定删除该" + selectArr.length + "条项目?", "提示", {
        confirmButtonText: "确 定",
        cancelButtonText: "取 消",
        type: "warning"
    }).then(async () => {
        state.loading = true
        let user_ids = []
        selectArr.forEach(it => user_ids.push(it.id))
        let params = {
            role_id: route.query.id,
            user_ids: user_ids
        }
        let res = await api.changeaxiosdata("delete_role_user", "post", params)
        if (res) {
            ElMessage({
                message: '删除成功!',
                type: 'success'
            })
            gettabledata()
        }
        state.loading = false
    }).catch(() => { })
}

//选择角色回调
let submitHandle = async (title, selectedList) => {
    state.loading = true
    let params = {}
    params.id = state.currentRow.id
    params.role_ids = selectedList.reduce((acc, curr, idx, arr) => {
        let str = idx === arr.length - 1 ? "" : ","
        return acc + curr.id + str
    }, '')
    let res = await api.changeaxiosdata("users", "patch", params)
    if (res) {
        gettabledata() //刷新页面
        ElMessage({
            message: '操作成功!',
            type: 'success'
        })
        state.loading = false
    }
}

//打开页面执行
let openFunction = async () => {
    let row = departmentRoles.value
    let title = row.department_name + ' - ' + route.query.name
    elTable_Options.pagename = title
    elTable_Options.addConditions = [{
        key: "role_ids",
        value: route.query.id
    }]
    nextTick(() => {
        gettabledata()
    })
}

let gettabledata = () => {
    nextTick(() => {
        table.value.getTableData()
    })
}
</script>

<style lang="scss" scoped></style>